package com.st.buy.cart.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.st.buy.cart.service.CartService;
import com.st.buy.manager.mapper.TbItemMapper;
import com.st.buy.pojo.TbItem;
import com.st.buy.util.json.JsonUtil;
import com.st.buy.util.pojo.BuyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 张双虎
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private TbItemMapper itemMapper;

    @Override
    public BuyResult deleteCart(long userId, Long itemId) {
        List<TbItem> cartList =getCartList(userId);
        //遍历删除  使用传统for循环遍历
        for(int i = 0;i<cartList.size();i++){
            if(cartList.get(i).getId().equals(itemId)){
                cartList.remove(i);
                break;
            }
        }
        //将购物车再次写入redis，替换原来的购物车
        String key = "CART_"+userId;
        stringRedisTemplate.opsForValue().set(key,JsonUtil.object2json(cartList));
        return BuyResult.ok();
    }

    public BuyResult cartAdd(long userId, Long itemId, int num) {
        //判断这个用户有没有购物车
        //没有就创建，有就获取  ---> 有购物车对象了
        List<TbItem> cartList = getCartList(userId); // 内存中肯定有购物车了。
        //判断这个商品是否已经在购物车中了
        boolean flag = false;//表示商品不存在
        for(TbItem item : cartList){
            if(item.getId().equals(itemId)){
                //如果存在就增加数量，
                flag = true;
                item.setNum(item.getNum()+num);
                break;
            }
        }
        if(!flag){
            //如果不存在就添加新商品
            TbItem item = itemMapper.selectById(itemId);
            //修改数量
            item.setNum(num);
            //加入购物车
            cartList.add(item);
        }
        //将购物车再次写入redis，替换原来的购物车
        String key = "CART_"+userId;
        stringRedisTemplate.opsForValue().set(key,JsonUtil.object2json(cartList));
        return BuyResult.ok();
    }

    /**
     * 获取一个购物车列表
     * @param userId
     * @return
     */
    public List<TbItem> getCartList(long userId){
        List<TbItem> cartList = new ArrayList<>();
        //从redis中获取
        String key ="CART_"+userId;
        if(stringRedisTemplate.hasKey(key)){
            String cartJson = stringRedisTemplate.opsForValue().get(key);
            //转换
            //cartList = JsonUtil.<TbItem>json2list(cartJson,TbItem.class);
            ObjectMapper mapper = new ObjectMapper();
            try {
                cartList =  mapper.readValue(cartJson, new TypeReference<List<TbItem>>() {});
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        //返回购物车
        return cartList;
    }

    @Override
    public BuyResult updateCart(long userId, Long itemId, int num) {
        //获取购物车列表
        List<TbItem> cartList = getCartList(userId);
        //遍历修改
        for (TbItem item: cartList){
            if(item.getId().equals(itemId)){
                //将数量修改成目标数量
                item.setNum(num);
            }
        }
        //将购物车写会redis
        //将购物车再次写入redis，替换原来的购物车
        String key = "CART_"+userId;
        stringRedisTemplate.opsForValue().set(key,JsonUtil.object2json(cartList));
        return BuyResult.ok();
    }
}
